package com.yhj.reggie.controller;

import com.yhj.reggie.common.R;
import com.yhj.reggie.entity.User;
import com.yhj.reggie.service.UserService;
import com.yhj.reggie.util.SMSUtils;
import com.yhj.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码: " + code);
//        SMSUtils.sendMessage("黑马旅游网","SMS_198917972", user.getPhone(), code);
//        session.setAttribute(user.getPhone(),code);
        //将验证码存放到缓存中
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        return R.success("发送验证码成功");
    }
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map,HttpSession session){
        String phone = map.get("phone");
        String userCode = map.get("code");


//        String  sessionCode = (String) session.getAttribute(phone);
        String  sessionCode = (String) redisTemplate.opsForValue().get(phone);

        User user = userService.loginUser(phone, userCode, sessionCode);

        if (user!=null){
            session.setAttribute("user",user.getId());
//            session.removeAttribute(phone);
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");

    }
}
